package com.qili.controller;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qili.core.utils.DictTypes;
import com.qili.entity.base.BaseDict;
import com.qili.entity.supervisor.SupervisorFileTemp;
import com.qili.entity.sys.SysRegion;
import com.qili.entity.sys.dto.SysUserDTO;
import com.qili.mapper.sys.SysUserMapper;
import com.qili.service.base.BaseCompanyService;
import com.qili.service.base.BaseDictService;
import com.qili.service.supervisor.SupervisorFileTempService;
import com.qili.service.supervisor.SupervisorPayRecordService;
import com.qili.service.supervisor.SupervisorProjectService;
import com.qili.service.supplier.SupplierProjectManagerService;
import com.qili.service.sys.SysRegionService;
import com.qili.util.*;
import io.swagger.annotations.ApiOperation;
import net.sf.jxls.transformer.XLSTransformer;
import org.apache.commons.io.FileUtils;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * @author zhaoyongke
 * @date 2021/5/17
 * @description   人员统计
 */
@RequestMapping("/search/personTj")
@Controller
public class PersonTjController {
    @Autowired
    BaseCompanyService baseCompanyService;
    @Autowired
    SysRegionService sysRegionService;
    @Autowired
    private SupervisorProjectService supervisorProjectService;
    @Autowired
    SupplierProjectManagerService supplierProjectManagerService;
    @Autowired
    SupervisorPayRecordService supervisorPayRecordService;
    @Autowired
    SupervisorFileTempService tempService;
    @Autowired
    UploadUtil uploadUtil;
    @Autowired
    BaseDictService baseDictService;

    @Autowired
    SysUserMapper  sysUserMapper;





    /**
    * @Author:zhaoyongke
    * @Description: 人员信息统计
    * @param model
    * @Date:9:19 2021/5/18
    */
    @GetMapping("/personInfoIndex")
    @RequiresPermissions("zn:jc:ry")
    public String personInfoIndex(Model model){
        //擅长领域
        List<BaseDict> doBestList = baseDictService.selectByTypeCode(DictTypes.DOBEST.getType());
        model.addAttribute("doBestList",doBestList);

        // 学历类型
        List<BaseDict> edulist = baseDictService.selectByTypeCode("XL001");
        //婚姻状况
        List<BaseDict> hyulist = baseDictService.selectByTypeCode("HYZK001");


        // 省
        List<SysRegion> provincelist = sysRegionService.selectListByLevelId("1");
        // 市
        List<SysRegion> citylist = sysRegionService.selectListByLevelId("2");
        //政治面貌：
        List<BaseDict> politicalList = baseDictService.selectByTypeCode(DictTypes.POLITIC.getType());
        model.addAttribute("politicalList",politicalList);
        //血型：
        List<BaseDict> bloodTypeList = baseDictService.selectByTypeCode(DictTypes.BLOODTYPE.getType());
        model.addAttribute("bloodTypeList",bloodTypeList);
        //星座：
        List<BaseDict> constellationList = baseDictService.selectByTypeCode(DictTypes.CONSTELLATION.getType());
        model.addAttribute("constellationList",constellationList);
        //属相
        List<BaseDict> zodiacList = baseDictService.selectByTypeCode(DictTypes.ZODIAC.getType());
        model.addAttribute("zodiacList",zodiacList);
        //岗位职称：
        List<BaseDict> gwzcList = baseDictService.selectByTypeCode(DictTypes.GWZC.getType());
        model.addAttribute("gwzcList",gwzcList);

        model.addAttribute("edulist",edulist);
        model.addAttribute("provincelist",provincelist);
        model.addAttribute("citylist",citylist);
        model.addAttribute("hyulist",hyulist);
        return "/decision/personTj/personInfoTjIndex";
    }
    //按人员统计
    @ApiOperation(value = "/selectPersonTjList", httpMethod = "GET", notes = "人员擅长领域")
    @GetMapping(value = "/selectPersonTjList")
    @ResponseBody
    public ReType selectPersonTjList(SysUserDTO dto, Model model, String page, String limit){
        Page<SysUserDTO> tPage = PageHelper.startPage(Integer.valueOf(page), Integer.valueOf(limit));
        ReType re = new ReType();
        List<SysUserDTO> sysUserDTOS = sysUserMapper.selectUserTjList(dto);
        for (int i = 0; i < sysUserDTOS.size(); i++) {
            String doBest = sysUserDTOS.get(i).getDoBest();
            if(StringUtil.isNotBlank(doBest)){
                String mainFzFieldstr = getLxText(doBest, DictTypes.DOBEST.getType());
                sysUserDTOS.get(i).setDoBest(mainFzFieldstr);
            }
        }
        re.setPageNum(Long.valueOf(page));
        re.setCount(tPage.getTotal());
        re.setData(sysUserDTOS);
        return re;

    }
    /**
     *  人员擅长领域统计
     * @param model
     * @return
     */
    @GetMapping("/doBestTjIndex")
    public String doBestTjIndex(Model model){
        //擅长领域
        List<BaseDict> doBestList = baseDictService.selectByTypeCode(DictTypes.DOBEST.getType());
        model.addAttribute("doBestList",doBestList);
        return "/decision/personTj/doBestTjIndex";
    }
    /*
    * @Author:zhaoyongke
    * @Description:
    * @param model
    * @Date:13:03 2021/5/17
    */
    @GetMapping("/doBestTjDetail")
    public String doBestTjIndex(Model model,SysUserDTO dto){
        String doBest = dto.getDoBest();
        //擅长领域
        model.addAttribute("doBest",doBest);
        return "/decision/personTj/doBestTjDetail";
    }


    /**
    * @Author:zhaoyongke
    * @Description: 按照人员擅长领域统计
    * @param dto
    * @param model
    * @param page
    * @param limit
    * @Date:10:46 2021/5/17
    */
    @ApiOperation(value = "/selectPersonDoBestList", httpMethod = "GET", notes = "人员擅长领域")
    @GetMapping(value = "/selectPersonDoBestList")
    @ResponseBody
    public ReType selectPersonDoBestList(SysUserDTO dto, Model model, String page, String limit){
        Page<SysUserDTO> tPage = PageHelper.startPage(Integer.valueOf(page), Integer.valueOf(limit));
         ReType re = new ReType();
        List<SysUserDTO> sysUserDTOS = sysUserMapper.selectUserTjByDoBest(dto);
        re.setPageNum(Long.valueOf(page));
        re.setCount(tPage.getTotal());
        re.setData(sysUserDTOS);
        return re;

    }
    /**
    * @Author:zhaoyongke
    * @Description: 按照人员擅长领域统计 详情
    * @param dto
    * @param model
    * @param page
    * @param limit
    * @Date:11:56 2021/5/17
    */
    @ApiOperation(value = "/selectPersonDoBestListDetail", httpMethod = "GET", notes = "人员擅长领域")
    @GetMapping(value = "/selectPersonDoBestListDetail")
    @ResponseBody
    public ReType selectPersonDoBestListDetail(SysUserDTO dto, Model model, String page, String limit){
        Page<SysUserDTO> tPage = PageHelper.startPage(Integer.valueOf(page), Integer.valueOf(limit));
        ReType re = new ReType();
        List<SysUserDTO> sysUserDTOS = sysUserMapper.selectUserTjByDoBestDetail(dto);
        for (int i = 0; i <sysUserDTOS.size() ; i++) {
            SysUserDTO sysUserDTO = sysUserDTOS.get(i);
            String doBestCode = sysUserDTO.getDoBest();
            String mainFzFieldstr = getLxText(doBestCode, DictTypes.DOBEST.getType());
            sysUserDTO.setDoBestName(mainFzFieldstr);
        }
        re.setPageNum(Long.valueOf(page));
        re.setCount(tPage.getTotal());
        re.setData(sysUserDTOS);
        return re;

    }
    public String getLxText(String field, String typecode) {
        List<BaseDict> codeList = baseDictService.selectByTypeCode(typecode);
        HashMap<String, String> mapbest = new HashMap();
        for (int i = 0; i < codeList.size(); i++) {
            mapbest.put(codeList.get(i).getBadtCode(), codeList.get(i).getBadtName());
        }
        //擅长领域
        List<String> dobest = StringUtil.split(field);
        List<String> best = new ArrayList<>();
        for (int i = 0; i < dobest.size(); i++) {
            String s = dobest.get(i);
            String scname = mapbest.get(s);
            best.add(scname);
        }
        String strbest = best.toString().replaceAll("\\[", "").replaceAll("\\]", "");
        return strbest;

    }


    //


    /**
     *  人员证书统计
     * @param model
     * @return
     */
    @GetMapping("/personCerTjIndex")
    public String selectUserTjByCert(Model model){
        return "/decision/personTj/personCerTjIndex";
    }

    /*
     * @Author:zhaoyongke
     * @Description:
     * @param model
     * @Date:13:03 2021/5/17
     */
    @GetMapping("/certTjDetail")
    public String certTjDetail(Model model,SysUserDTO dto){
        String certName = dto.getCertName();
        String id = dto.getId();
        if(StringUtil.isNotBlank(certName)){
            model.addAttribute("certName",certName);
        }else  if(StringUtil.isNotBlank(id)){
            model.addAttribute("id",id);
        }

        return "/decision/personTj/certTjDetail";
    }


    /**
     * @Author:zhaoyongke
     * @Description: 按照人员持有证书统计
     * @param dto
     * @param model
     * @param page
     * @param limit
     * @Date:10:46 2021/5/17
     */
    @ApiOperation(value = "/selectPersonCertList", httpMethod = "GET", notes = "人员持有证书统计")
    @GetMapping(value = "/selectPersonCertList")
    @ResponseBody
    public ReType selectPersonCertList(SysUserDTO dto, Model model, String page, String limit){
        Page<SysUserDTO> tPage = PageHelper.startPage(Integer.valueOf(page), Integer.valueOf(limit));
        ReType re = new ReType();
        List<SysUserDTO> sysUserDTOS = sysUserMapper.selectUserTjByCert(dto);
        re.setPageNum(Long.valueOf(page));
        re.setCount(tPage.getTotal());
        re.setData(sysUserDTOS);
        return re;

    }

    /**
     * @Author:zhaoyongke
     * @Description: 按照人员持有证书统计详情列表
     * @param dto
     * @param model
     * @param page
     * @param limit
     * @Date:10:46 2021/5/17
     */
    @ApiOperation(value = "/selectUserTjByCertDetail", httpMethod = "GET", notes = "人员持有证书统计详情列表")
    @GetMapping(value = "/selectUserTjByCertDetail")
    @ResponseBody
    public ReType selectUserTjByCertDetail(SysUserDTO dto, Model model, String page, String limit){
        Page<SysUserDTO> tPage = PageHelper.startPage(Integer.valueOf(page), Integer.valueOf(limit));
        ReType re = new ReType();
        List<SysUserDTO> sysUserDTOS = sysUserMapper.selectUserTjByCertDetail(dto);

        re.setPageNum(Long.valueOf(page));
        re.setCount(tPage.getTotal());
        re.setData(sysUserDTOS);
        return re;

    }

    /**
    * @Author:zhaoyongke
    * @Description: 查询部门信息
    * @param request
    * @Date:16:59 2021/5/18
    */
    @GetMapping(value = "getdeptName")
    @ResponseBody
    public JsonUtil getdeptName(HttpServletRequest request) {
        JsonUtil re = new JsonUtil();
        try {
            SysUserDTO dto = new SysUserDTO();
            List<SysUserDTO> data = sysUserMapper.selectdeptList(dto);
            re.setFlag(true);
            re.setData(data);
            return re;
        } catch (Exception e) {
            e.printStackTrace();
            re.setFlag(false);
            re.setMsg("获取数据异常！！" + e.getMessage());
            return re;
        }
    }

    /**
     * 人员详情
     * @param model
     * @param userId
     * @return
     */
    @RequestMapping("details")
    public String selectDetails(Model model,String userId){
        List<SysUserDTO> sysUserDTOS= new ArrayList<>();
        SysUserDTO sys=new SysUserDTO();
        sys.setId(userId);
        if(StringUtil.isNotBlank(userId)){
            sysUserDTOS = sysUserMapper.selectUserTjList(sys);
        }
        for (int i = 0; i < sysUserDTOS.size(); i++) {
            String doBest = sysUserDTOS.get(i).getDoBest();
            if(StringUtil.isNotBlank(doBest)){
                String mainFzFieldstr = getLxText(doBest, DictTypes.DOBEST.getType());
                sysUserDTOS.get(i).setDoBest(mainFzFieldstr);
            }
        }
        model.addAttribute("user",sysUserDTOS.get(0));
        return "/decision/personTj/personInfoTjDetails";
    }

    /**
     *按人员统计导出
     * @param dto
     * @param response
     * @return
     */
    @RequestMapping("exportTable")
    public void exportTable(SysUserDTO dto, HttpServletResponse response){
        HashMap map=new HashMap<>();
        String fileName="人员信息统计_按人员统计"+DateUtil.getCurrentDateNoSpliter();
        List<SysUserDTO> sysUserDTOS = sysUserMapper.selectUserTjList(dto);
        for (int i = 0; i < sysUserDTOS.size(); i++) {
            String doBest = sysUserDTOS.get(i).getDoBest();
            if(StringUtil.isNotBlank(doBest)){
                String mainFzFieldstr = getLxText(doBest, DictTypes.DOBEST.getType());
                sysUserDTOS.get(i).setDoBest(mainFzFieldstr);
            }
            String sex= sysUserDTOS.get(i).getSex();
            if("1".equals(sex)) {
                sysUserDTOS.get(i).setSex("男");
            }else if("0".equals(sex)){
                sysUserDTOS.get(i).setSex("女");
            }
            String bussTravel= sysUserDTOS.get(i).getBussTravel();
            if("1".equals(bussTravel)) {
                sysUserDTOS.get(i).setBussTravel("是");
            }else if("0".equals(bussTravel)){
                sysUserDTOS.get(i).setBussTravel("否");
            }
            sysUserDTOS.get(i).setXuhao(i+1);
        }
        map.put("name","人员信息统计_按人员统计");
        map.put("lists",sysUserDTOS);
        try {
            ExcelExportUtil.exportExcel(response,map,fileName,"98001");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     *人员统计预览
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping("viewTable")
    public JsonUtil viewTable(SysUserDTO dto,HttpServletRequest request, HttpServletResponse response) {
        JsonUtil result = new JsonUtil();
        HashMap map=new HashMap<>();
        File formExcel =null;
        String fileName="人员信息统计_按人员统计"+DateUtil.getCurrentDateNoSpliter();
        try{
            List<SysUserDTO> sysUserDTOS = sysUserMapper.selectUserTjList(dto);
            for (int i = 0; i < sysUserDTOS.size(); i++) {
                String doBest = sysUserDTOS.get(i).getDoBest();
                if(StringUtil.isNotBlank(doBest)){
                    String mainFzFieldstr = getLxText(doBest, DictTypes.DOBEST.getType());
                    sysUserDTOS.get(i).setDoBest(mainFzFieldstr);
                }
                String sex= sysUserDTOS.get(i).getSex();
                if("1".equals(sex)) {
                    sysUserDTOS.get(i).setSex("男");
                }else if("0".equals(sex)){
                    sysUserDTOS.get(i).setSex("女");
                }
                String bussTravel= sysUserDTOS.get(i).getBussTravel();
                if("1".equals(bussTravel)) {
                    sysUserDTOS.get(i).setBussTravel("是");
                }else if("0".equals(bussTravel)){
                    sysUserDTOS.get(i).setBussTravel("否");
                }
                sysUserDTOS.get(i).setXuhao(i+1);
            }
            map.put("name","人员信息统计_按人员统计");
            map.put("lists",sysUserDTOS);
            formExcel = createFormExcel("98001", fileName, map);
            String tempFilePath = uploadUtil.getTempPath()+File.separator+ new Date().getTime()
                    +File.separator+fileName+formExcel.getName().substring(formExcel.getName().lastIndexOf("."));
            File tempFile = new File(tempFilePath);
            if(!tempFile.getParentFile().exists()){
                tempFile.getParentFile().mkdirs();
            }
            tempFile.createNewFile();
            FileUtils.copyFile(formExcel,tempFile);
            formExcel.delete();
            SupervisorFileTemp temp = new SupervisorFileTemp();
            temp.setUrl(tempFile.getPath());
            temp.setFileName(tempFile.getName());
            temp.setFileType(tempFile.getName().substring(tempFile.getName().lastIndexOf(".")));
            temp.setType("tz");
            tempService.insertSelective(temp);
            result.setFlag(true);
            result.setData(temp.getId());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }


    /**
     *按擅长领域统计导出
     * @param dto
     * @param response
     * @return
     */
    @RequestMapping("exportCount")
    public void export(SysUserDTO dto, HttpServletResponse response) {
        HashMap map = new HashMap<>();
        String fileName = "人员信息统计_按擅长领域统计" + DateUtil.getCurrentDateNoSpliter();
        List<SysUserDTO> sysUserDTOS = sysUserMapper.selectUserTjByDoBest(dto);
        for (int i = 0; i < sysUserDTOS.size(); i++) {
            sysUserDTOS.get(i).setXuhao(i + 1);
        }
        map.put("name", "人员信息统计_按擅长领域统计");
        map.put("lists", sysUserDTOS);
        try {
            ExcelExportUtil.exportExcel(response, map, fileName, "98002");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     *按证书拥有人统计导出
     * @param dto
     * @param response
     * @return
     */
   @RequestMapping("exportCountUser")
   public void exportCountUser(SysUserDTO dto, HttpServletResponse response) {
       HashMap map = new HashMap<>();
       String fileName = "人员信息统计_按证书拥有人统计" + DateUtil.getCurrentDateNoSpliter();
       List<SysUserDTO> sysUserDTOS = sysUserMapper.selectUserByCert(dto);
       for (int i = 0; i < sysUserDTOS.size(); i++) {
           sysUserDTOS.get(i).setXuhao(i + 1);
       }
       map.put("name", "人员信息统计_按证书拥有人统计");
       map.put("lists", sysUserDTOS);
       try {
           ExcelExportUtil.exportExcel(response, map, fileName, "98003");
       } catch (IOException e) {
           e.printStackTrace();
       }
   }


    /**
     *按擅长领域预览
     * @param request
     * @param response
     * @return
     */
     @ResponseBody
     @RequestMapping("viewCount")
     public JsonUtil viewCount(SysUserDTO dto, HttpServletRequest request, HttpServletResponse response) {
         JsonUtil result = new JsonUtil();
         HashMap map = new HashMap<>();
         File formExcel = null;
         String fileName = "人员信息统计_按擅长领域统计" + DateUtil.getCurrentDateNoSpliter();
         try {
             List<SysUserDTO> sysUserDTOS = sysUserMapper.selectUserTjByDoBest(dto);
             for (int i = 0; i < sysUserDTOS.size(); i++) {
                /* String doBest = sysUserDTOS.get(i).getDoBest();
                 if(StringUtil.isNotBlank(doBest)){
                     String mainFzFieldstr = getLxText(doBest, DictTypes.DOBEST.getType());
                     sysUserDTOS.get(i).setDoBest(mainFzFieldstr);
                 }*/
                 sysUserDTOS.get(i).setXuhao(i+1);
             }
             map.put("name", "人员信息统计_按擅长领域统计");
             map.put("lists", sysUserDTOS);
             formExcel = createFormExcel("98002", fileName, map);
             String tempFilePath = uploadUtil.getTempPath() + File.separator + new Date().getTime()
                     + File.separator + fileName + formExcel.getName().substring(formExcel.getName().lastIndexOf("."));
             File tempFile = new File(tempFilePath);
             if (!tempFile.getParentFile().exists()) {
                 tempFile.getParentFile().mkdirs();
             }
             tempFile.createNewFile();
             FileUtils.copyFile(formExcel, tempFile);
             formExcel.delete();
             SupervisorFileTemp temp = new SupervisorFileTemp();
             temp.setUrl(tempFile.getPath());
             temp.setFileName(tempFile.getName());
             temp.setFileType(tempFile.getName().substring(tempFile.getName().lastIndexOf(".")));
             temp.setType("tz");
             tempService.insertSelective(temp);
             result.setFlag(true);
             result.setData(temp.getId());
         } catch (IOException e) {
             e.printStackTrace();
         }
         return result;
     }

    /**
     *按证书拥有人预览
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping("viewCountUser")
    public JsonUtil viewCountUser(SysUserDTO dto, HttpServletRequest request, HttpServletResponse response) {
        JsonUtil result = new JsonUtil();
        HashMap map = new HashMap<>();
        File formExcel = null;
        String fileName = "人员信息统计_按证书拥有人统计" + DateUtil.getCurrentDateNoSpliter();
        try {
            List<SysUserDTO> sysUserDTOS = sysUserMapper.selectUserByCert(dto);
            for (int i = 0; i < sysUserDTOS.size(); i++) {
                sysUserDTOS.get(i).setXuhao(i+1);
            }
            map.put("name", "人员信息统计_按证书拥有人统计");
            map.put("lists", sysUserDTOS);
            formExcel = createFormExcel("98003", fileName, map);
            String tempFilePath = uploadUtil.getTempPath() + File.separator + new Date().getTime()
                    + File.separator + fileName + formExcel.getName().substring(formExcel.getName().lastIndexOf("."));
            File tempFile = new File(tempFilePath);
            if (!tempFile.getParentFile().exists()) {
                tempFile.getParentFile().mkdirs();
            }
            tempFile.createNewFile();
            FileUtils.copyFile(formExcel, tempFile);
            formExcel.delete();
            SupervisorFileTemp temp = new SupervisorFileTemp();
            temp.setUrl(tempFile.getPath());
            temp.setFileName(tempFile.getName());
            temp.setFileType(tempFile.getName().substring(tempFile.getName().lastIndexOf(".")));
            temp.setType("tz");
            tempService.insertSelective(temp);
            result.setFlag(true);
            result.setData(temp.getId());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }





    /**
     * 创建表单临时表格文件
     * @param fileName
     * @param dataMap
     * @return
     */
    public File createFormExcel(String ptid,String fileName,HashMap dataMap){
        try {
            // 获取模板信息
            String srcFilePath = FilePathUtil.getPathConfigTemplateFile(ptid);
            //生成的临时导出文件
            File destFile  = File.createTempFile(fileName, ".xls");
            //  开始转换。利用  transformer 转到Excel
            XLSTransformer transformer = new XLSTransformer();
            // 参数：srcFilePath：模板源文件    cMap：需要导出的数据   destFile.getAbsolutePath()：下载的目标文件
            transformer.transformXLS(srcFilePath, dataMap, destFile.getAbsolutePath());
            return destFile;
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InvalidFormatException e) {
            e.printStackTrace();
        }
        return null;
    }
}
